
package com.ppt.convert.util;

import cn.hutool.core.date.DateUtil;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 签名工具类
 * @author xxu
 *
 */
public class SignCrypt
{
	
	/**
	 * 
	 * @description 签名加密
	 *            请求参数列表
	 * @param appSecret
	 *            加密key
	 * @return String
	 * @author hswei
	 * @createDate 2014-4-28
	 */
	public static String createSign( TreeMap<String, String> params, String appSecret )
	{
		// 排序
		//Collections.sort( paramList );
		
//		StringBuilder sb = new StringBuilder();
//		
//		for (Map.Entry<String, String> entry : params.entrySet()) {
//			sb.append(entry.getValue());
//		}
//		
//		String paramsStr = accessToken + replace_ENTER_NEWLINE_TAB_Symbol( sb.toString() ) + accessToken;
		
		try
		{
			return HmacMD5.hmacMd5( sortAndFormat(params).getBytes( "UTF-8" ), appSecret.getBytes( "UTF-8" ) );
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	 /**
     * 参数排序及格式化
     * @param params
     * @return
     */
    private static String sortAndFormat(TreeMap<String, String> params)
    {
		StringBuffer sb = new StringBuffer();
		int flag = 0;
		for(String key:params.keySet())
		{
			if(flag==0)
			{
				sb.append(key+"="+params.get(key));
			}else
			{
				sb.append("&"+key+"="+params.get(key));
			}
			
			flag++;
		}
		return sb.toString();
    }
    
    
	/**
	 * 验证签名
	 * @param sign
	 * @param appSecret
	 * @param params
	 * @return
	 */
	public static boolean verifySign(String sign,String appSecret,TreeMap<String, String> params)
	{
		return sign.equals(createSign(params,appSecret));
	}
	
	private static Pattern p = Pattern.compile( "\t|\r|\n" );
	
	/**
	 * 去除回车符、换行符、制表符
	 * 
	 * @param content
	 * @return
	 */
	private static String replace_ENTER_NEWLINE_TAB_Symbol( String content )
	{
		
		if( content == null )
		{
			return null;
		}
		else
		{
			Matcher m = p.matcher( content );
			
			return m.replaceAll( "" );
		}
		
	}
	
	public static void main(String[] args) {
		 TreeMap<String, String> p = new TreeMap<>();
		String time = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        p.put("appKey", "759938614CFC4662B9E4520243A10155");
        p.put("timestamp", "20180813111111");
        p.put("isOpen", "T");
        String sign = SignCrypt.createSign(p, "B7FEADAB04384CF190FE5BD4F9363DD5");
		System.out.println(sign);
	}
	
}
